import { QueryKey, useMutation, useQuery } from "react-query";
import { useHttp } from "./http";
import { cleanObject } from "./index";
import { Kanban } from "../type/kanban";
import { useDeleteConfig } from "./use-optimistic-options";

export const useKanban = (param?: Partial<Kanban>) => {
    const client = useHttp();
    return useQuery<Kanban[]>(['kanbans', param],
        () => client('kanbans', {
            data: cleanObject(param || {})
        })
    )
};

export const useKanbanDetail = (id?: number) => {
    const client = useHttp();
    return useQuery(
        ['kanbans', { id }],
        () => client(`kanbans/${id}`),
        {
            enabled: Boolean(id)
        }
    )
}

export const useDeleteKanban = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        ({ id }: { id: number }) =>
            client(`kanbans/${id}`, {
                method: "DELETE",
            }),
        useDeleteConfig(queryKey)
    )
}

export const useAddKanban = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Kanban>) =>
            client(`kanbans`, {
                method: "POST",
                data: params
            }),
        useDeleteConfig(queryKey)
    )
}

export const useEditKanban = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Kanban>) =>
            client(`kanbans/${params.id}`, {
                method: "PATCH",
                data: params
            }),
        useDeleteConfig(queryKey)
    )
}